// pages/quanxian/quanxian.js
var common = require('../../js/common.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: '权限分配'
    })

    this.setData({
      user_id: options.id
    })
    //获取积分
    var that = this;
    common.request(app.globalData.localUrl, 'quanxian', { user_id: options.id, yiyuan_id: wx.getStorageSync('yiyuan_id')},
      function(res) {
        console.log('权限遍历', res)
        if (res.data.code == 1) {
          that.setData({
            quanxian: res.data.data
          })
        }
      }, 'rtype= post');
  },

  djchang: function(e) {
    var index = e.target.dataset.index;
    var quanxian = this.data.quanxian;

    if (quanxian[index].is_have == 1) {

      quanxian[index].is_have = 0;

    } else {
      quanxian[index].is_have = 1;
    }
    this.setData({
      quanxian: quanxian
    })
  },


  // 提交修改

  formSubmit: function(e) {
    var that = this;

    wx.showLoading({
      title: '提交中',
      mask: true
    })


    if (!that.data.user_id) {
      wx.showToast({
        title: '员工异常',
        icon: 'none',
        duration: 1500
      })
      return;
    }


    var qx = [];
    var i = 0;
    var xz = '';
    for (var index in that.data.quanxian) {
      if (that.data.quanxian[index].is_have == 1) {
        qx[i] = that.data.quanxian[index].id;
        i++;
      }

    }

    xz = qx.join(',');
    var data = {
      user_id: that.data.user_id,
      json: xz,
      yiyuan_id: wx.getStorageSync('yiyuan_id'),
    };
    console.log('权限修改数据', data)
    console.log('数组', qx)
    common.request(app.globalData.localUrl, 'authedit', data,
      function(res) {
        console.log('修改权限', res)
        if (res.data.code == 1) {
          wx.showToast({
            title: '修改权限成功',
            icon: 'success',
            mask: true
          })

          setTimeout(function() {
            var pages = getCurrentPages(); // 当前页面
            var beforePage = pages[pages.length - 2]; // 前一个页面
            // console.log("beforePage");
            // console.log(beforePage);
            wx.navigateBack({
              success: function() {
                beforePage.onLoad(); // 执行前一个页面的onLoad方法
              }
            });
          }, 1500);

        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1500
          })
        }
      }
    );
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})